package cn.com.nes.site.service.agent.impl;

import cn.com.nes.mybatis.agent.agent.entity.AgentGrantProduct;
import cn.com.nes.mybatis.agent.agent.entity.AgentGrantType;
import cn.com.nes.mybatis.agent.agent.mapper.AgentGrantProductMapper;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.agent.grant.AgentGrantTypeEnum;
import cn.com.nes.site.service.agent.AgentGrantProductService;
import cn.com.nes.site.service.agent.AgentGrantTypeService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author yishuai
* @description 针对表【agent_grant_product(代理授权产品范围表;一个授权可以设置多个产品)】的数据库操作Service实现
* @createDate 2024-12-05 10:55:14
*/
@Service
public class AgentGrantProductServiceImpl extends ServiceImpl<AgentGrantProductMapper, AgentGrantProduct> implements AgentGrantProductService {

    @Resource
    private AgentGrantTypeService agentGrantTypeService;

    @Override
    public Set<Long> queryAgentRelationshipIds(String productUuid) {
        // 查询当前产品所属的授权关系
        QueryWrapper<AgentGrantProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("grant_id");
        queryWrapper.eq("product_uuid", productUuid);
        queryWrapper.eq("deleted", DeleteEnum._0.getKey());
        List<AgentGrantProduct> agentGrantProducts = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(agentGrantProducts)) {
            return new HashSet<>();
        }

        Set<Long> grantIdSet = agentGrantProducts.stream().map(AgentGrantProduct::getGrantId).collect(Collectors.toSet());
        Date now = new Date();

        // 查询授权关系所属的代理关系
        QueryWrapper<AgentGrantType> grantTypeQueryWrapper = new QueryWrapper<>();
        grantTypeQueryWrapper.select("agent_relationship_id");
        grantTypeQueryWrapper.eq("deleted", DeleteEnum._0.getKey());
        grantTypeQueryWrapper.eq("grant_type", AgentGrantTypeEnum.MAINTENANCE.getKey());
        grantTypeQueryWrapper.in("grant_id", grantIdSet);
        grantTypeQueryWrapper.le("start_time", now);    // 开始时间早于（小于）现在
        grantTypeQueryWrapper.ge("end_time", now);      // 结束时间晚于（大于）现在
        List<AgentGrantType> agentGrantTypeList = agentGrantTypeService.list(grantTypeQueryWrapper);
        if (CollectionUtil.isEmpty(agentGrantTypeList)) {
            return new HashSet<>();
        }
        return agentGrantTypeList.stream().map(AgentGrantType::getAgentRelationshipId).collect(Collectors.toSet());
    }
}
